<template>
  <view class="uploadImg">
    <view class="cu-form-group">
      <view class="grid col-4 grid-square flex-sub">
        <view class="bg-img" v-for="(item, index) in imgFile" :key="index" @tap="ViewImage(index)"
          :data-url="imgFile[index]">
          <image style="border: 1rpx solid #e5e5e5;" :src="getImgUrl(imgFile[index])" mode="aspectFill"></image>
          <view class="cu-tag bg-red" @tap.stop="DelImg" :data-index="index" v-show="isUpload"><text
              class="cuIcon-close"></text></view>
        </view>
        <view class="solids" @tap="ChooseImage" v-if="imgFile.length < imgcount" v-show="isUpload"><text
            class="cuIcon-add"></text></view>
      </view>
    </view>
  </view>
</template>

<script>
import { baseApiUrl } from '@/config.js';
export default {
  name: 'uploadImg',
  props: {
    imgList: {
      type: Array,
      default: () => {
        return [];
      }
    },
    imgPath: {
      type: String,
      default: '/common/upload'
    },
    fieldName: {
      type: String,
      default: 'file'
    },
    imgcount: {
      type: Number,
      default: 1
    },
    isUpload: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      uploadFile: [],
      imgFile: []
    };
  },
  methods: {
    ChooseImage() {
      // this.uploadFile = []
      // this.imgFile = []
      uni.chooseImage({
        count: this.imgcount, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success: res => {
          console.log(res, this.uploadFile.length)
          if (this.uploadFile.length + res.tempFilePaths.length <= this.imgcount) {
            res.tempFilePaths.forEach(item => {
              const uploadTask = uni.uploadFile({
                url: baseApiUrl + this.imgPath,
                name: this.fieldName,
                header: {
                  Authorization: this.$store.state.login.userInfo.token,
                },
                filePath: item,
                success: uploadFileRes => {
                  this.imgFile.push(baseApiUrl + JSON.parse(uploadFileRes.data).fileName);
                  this.uploadFile.push(JSON.parse(uploadFileRes.data).fileName);
                  this.$emit("changeImage", this.uploadFile)
                },
                fail: err => {
                  uni.showToast({
                    title: err,
                    icon: 'none',
                    duration: 2000
                  });
                }
              });
              uploadTask.onProgressUpdate(res => {
              });
            })
          } else {
            uni.showToast({
              title: '所选数量超过最大长度，请重新选择上传',
              icon: 'none',
              duration: 2000
            });
          }


        }
      });
    },
    getImgUrl(url) {
      if (url) {
        if (url.indexOf('http') < 0) {
          url = this.$baseApiUrl + url;
        }
        url = url.replace(/\\/g, '/');
        return encodeURI(url);
      } else {
        return url;
      }
    },

    // 预览图片
    ViewImage(index) {
      var path = this.imgFile;
      path = path.map(item => {
        return this.getImgUrl(item);
      });
      uni.previewImage({
        urls: path,
        current: index
      });
    },
    DelImg(e) {
      uni.showModal({
        title: '提示',
        content: '确定要删除这张图片吗？',
        cancelText: '取消',
        confirmText: '去掉',
        success: res => {
          if (res.confirm) {
            this.imgFile.splice(e.currentTarget.dataset.index, 1);
            this.uploadFile.splice(e.currentTarget.dataset.index, 1);
            this.$emit("changeImage", this.uploadFile)
          }
        }
      });
    }
  },
  watch: {
    imgList: {
      handler(newVal, oldVal) {
        newVal.forEach(item => {
          this.imgFile.push(baseApiUrl + item);
          this.uploadFile.push(item);
        });
      },
      immediate: true
    }
  },
  mounted() {

  }
};
</script>

<style lang="scss" scoped>
.uploadImg {
  width: 100%;
  // height: 200rpx;
  padding: 30rpx;
}

.uni-status-bar {
  display: block;
  width: 100%;
  height: 20px;
  height: var(--status-bar-height);
  background-color: #d8151f;
}
</style>
